<template>

  <!--头: 引入 CommonHead 子组件-->
  <header class="update-personal-head">
    <CommonHead title="修改用户昵称"/>
  </header>

  <br/>

  <!--体: 使用卡片单元格布局修改界面-->
  <section class="update-personal-body">
    <van-cell-group inset>
      <!--用户昵称: 双绑用户昵称，背景提示字，左图标，垂直居中，可清除，自动获取焦点，关闭提示-->
      <van-field label="用户昵称" v-model="nickName" placeholder="请输入用户昵称"
                 left-icon="edit" center clearable autofocus autocomplete="off">
        <template #button>
          <!--按钮: 小号，线条，主要蓝，点击时触发-->
          <van-button size="small" type="primary" @click="updateNickName">保存</van-button>
        </template>
      </van-field>
    </van-cell-group>
  </section>

</template>

<script setup>
import CommonHead from "@/components/CommonHead";
import {UPDATE_PERSONAL} from '@/api/user';
import {useStore} from "vuex";
import router from "@/router";
import {onBeforeMount, shallowRef} from "vue";
import {showFailToast, showSuccessToast} from "vant";
import {SUCCESS} from "@/constant";

/* ==================== method ==================== */

// data: Vuex实例，直接使用useStore()会报错
let vuex = useStore();

// data: 用户主键
const userId = sessionStorage.getItem('userId');

// data: 用户昵称，转为字符串是为了方便正则校验
let nickName = shallowRef(router.currentRoute.value.query['nickName'] + "");

/* ==================== method ==================== */

// method: 修改用户昵称
async function updateNickName(){
  // 规则校验
  if (!/^[a-zA-Z0-9_-]{2,15}$/.test(nickName.value)) {
    showFailToast("格式有误: 用户昵称长度为2-15个字符");
    return;
  }
  // 异步修改用户昵称
  let result = await UPDATE_PERSONAL({'nickName': nickName.value});
  let resp = result['data'];
  if (resp.code === SUCCESS) {
    showSuccessToast("修改成功");
    await router.push("/Personal");
  } else {
    showFailToast(resp.message + ': ' + resp.data);
  }
}

/* ==================== beforeMount ==================== */

// beforeMount: DOM挂载前，判断用户是否登录
onBeforeMount(() => {
  if (!vuex.state['loginFlag']) {
    showFailToast('请先登录');
    setTimeout(() => router.push("/LoginByAccount"), 1000);
  }
});
</script>

<style scoped lang="scss">

</style>